﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using NuSoft.SistemaGestionPersonal.WinFormsUI.BusinessEntities;

namespace NuSoft.SistemaGestionPersonal.WinFormsUI
{
    public partial class NewUpdateEmployeeForm : Form
    {
        public Employee Employee { get; set; }

        public NewUpdateEmployeeForm(Employee employee = null)
        {
            Employee = employee;

            InitializeComponent();
        }

        private void NewUpdateEmployee_Load(object sender, EventArgs e)
        {
            EmployeeEntryDateDateTimePicker.MaxDate = DateTime.Today;
            EmployeeBirthDateDateTimePicker.MaxDate = new DateTime(DateTime.Today.Year - 23, DateTime.Today.Month, DateTime.Today.Day);
            EmployeeBirthDateDateTimePicker.MinDate = new DateTime(DateTime.Today.Year - 70, DateTime.Today.Month, DateTime.Today.Day);

            if (Employee != null)
            {
                Text = "Editar operario";
                EmployeeIdTextBox.Text = Employee.Id.ToString();
                EmployeeEntryDateDateTimePicker.Value = Employee.EntryDate;
                EmployeeFirstNameTextBox.Text = Employee.FirstName;
                EmployeeMiddleNameTextBox.Text = Employee.MiddleName;
                EmployeeFirstSurnameTextBox.Text = Employee.FirstSurname;
                EmployeeSecondSurnameTextBox.Text = Employee.SecondSurname;
                EmployeeDocumentTypeTextBox.Text = Employee.DocumentType;
                EmployeeDocumentNumberTextBox.Text = Employee.DocumentNumber;
                EmployeeBirthDateDateTimePicker.Value = Employee.BirthDate;
                if (Employee.MaritalStatus != MaritalStatus.Undefined)
                {
                    EmployeeMaritalStatusComboBox.SelectedItem = Employee.MaritalStatus.ToLocalizedString();
                }
                if (Employee.Position != null)
                {
                    if (Employee.Position.PositionCategory != PositionCategory.Undefined)
                    {
                        EmployeePositionCategoryComboBox.SelectedItem = Employee.Position.PositionCategory.ToLocalizedString();
                        foreach (var position in Repository.Instance.Positions.Where(position => position.PositionCategory == Employee.Position.PositionCategory))
                        {
                            EmployeePositionComboBox.Items.Add(position.Name);
                        }
                        if (EmployeePositionComboBox.Items.Count > 0)
                        {
                            EmployeePositionComboBox.Enabled = true;
                        }
                        if (!string.IsNullOrEmpty(Employee.Position.Name))
                        {
                            EmployeePositionComboBox.SelectedItem = Employee.Position.Name;
                        }
                    }
                }
                EmployeeFirstContactFirstNameTextBox.Text = Employee.FirstContactFirstName;
                EmployeeFirstContactSurnameTextBox.Text = Employee.FirstContactSurname;
                EmployeeFirstContactTelephoneNumberTextBox.Text = Employee.FirstContactTelephoneNumber;
                EmployeeFirstContactRelationshipTextBox.Text = Employee.FirstContactRelationship;
            }
            else
            {
                Text = "Nuevo operario";
                EmployeeIdTextBox.Text = Repository.Instance.Employees.Count > 0 ? (Repository.Instance.Employees.Max(employee => employee.Id) + 1).ToString() : "1";
                EmployeeEntryDateDateTimePicker.Value = DateTime.Today;
            }
        }

        private void EmployeePositionCategoryComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            var positionCategory = EnumHelper.LocalizedStringToPositionCategory((string)EmployeePositionCategoryComboBox.SelectedItem);
            EmployeePositionComboBox.Items.Clear();
            foreach (var position in Repository.Instance.Positions.Where(position => position.PositionCategory == positionCategory))
            {
                EmployeePositionComboBox.Items.Add(position.Name);
            }
            EmployeePositionComboBox.Enabled = EmployeePositionComboBox.Items.Count > 0;
        }

        private void NamesTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar);
        }

        private void EmployeeFirstNameTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(EmployeeFirstNameTextBox.Text))
            {
                MasterErrorProvider.SetError(EmployeeFirstNameTextBox, "No se ha ingresado el primer nombre del operario");
            }
            else
            {
                MasterErrorProvider.SetError(EmployeeFirstNameTextBox, null);
            }
        }

        private void EmployeeMiddleNameTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(EmployeeMiddleNameTextBox.Text))
            {
                MasterErrorProvider.SetError(EmployeeMiddleNameTextBox, "No se ha ingresado el segundo nombre del operario");
            }
            else
            {
                MasterErrorProvider.SetError(EmployeeMiddleNameTextBox, null);
            }
        }

        private void EmployeeFirstSurnameTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(EmployeeFirstSurnameTextBox.Text))
            {
                MasterErrorProvider.SetError(EmployeeFirstSurnameTextBox, "No se ha ingresado el primer apellido del operario");
            }
            else
            {
                MasterErrorProvider.SetError(EmployeeFirstSurnameTextBox, null);
            }
        }

        private void EmployeeSecondSurnameTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(EmployeeSecondSurnameTextBox.Text))
            {
                MasterErrorProvider.SetError(EmployeeSecondSurnameTextBox, "No se ha ingresado el segundo apellido del operario");
            }
            else
            {
                MasterErrorProvider.SetError(EmployeeSecondSurnameTextBox, null);
            }
        }

        private void EmployeeDocumentNumberTextBox_Validating(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(EmployeeDocumentNumberTextBox.Text))
            {
                MasterErrorProvider.SetError(EmployeeDocumentNumberTextBox, "No se ha ingresado el número de documento del operario");
            }
            else if (Repository.Instance.Employees.Any(employee => employee.DocumentNumber.Equals(EmployeeDocumentNumberTextBox.Text, StringComparison.OrdinalIgnoreCase)))
            {
                MasterErrorProvider.SetError(EmployeeDocumentNumberTextBox, "Documento ya existente en el sistema");
            }
            else
            {
                MasterErrorProvider.SetError(EmployeeDocumentNumberTextBox, null);
            }
        }

        private void EmployeeFirstContactFirstNameTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(EmployeeFirstContactFirstNameTextBox.Text))
            {
                MasterErrorProvider.SetError(EmployeeFirstContactFirstNameTextBox, "No se ha ingresado el nombre del primer contacto");
            }
            else
            {
                MasterErrorProvider.SetError(EmployeeFirstContactFirstNameTextBox, null);
            }
        }

        private void EmployeeFirstContactSurnameTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(EmployeeFirstContactSurnameTextBox.Text))
            {
                MasterErrorProvider.SetError(EmployeeFirstContactSurnameTextBox, "No se ha ingresado el apellido del primer contacto");
            }
            else
            {
                MasterErrorProvider.SetError(EmployeeFirstContactSurnameTextBox, null);
            }
        }

        private void EmployeeFirstContactTelephoneNumberTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar);
        }

        private void EmployeeFirstContactTelephoneNumberTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(EmployeeFirstContactTelephoneNumberTextBox.Text))
            {
                MasterErrorProvider.SetError(EmployeeFirstContactTelephoneNumberTextBox, "No se ha ingresado el teléfono del primer contacto");
            }
            else
            {
                MasterErrorProvider.SetError(EmployeeFirstContactTelephoneNumberTextBox, null);
            }
        }

        private void AcceptNewUpdateEmployeeButton_Click(object sender, EventArgs e)
        {
            ValidateChildren();

            Control[] controlsToCheck =
            {
                EmployeeFirstNameTextBox,
                EmployeeFirstSurnameTextBox,
                EmployeeSecondSurnameTextBox,
                EmployeeFirstContactFirstNameTextBox,
                EmployeeFirstContactSurnameTextBox,
                EmployeeFirstContactTelephoneNumberTextBox
            };
            string error = controlsToCheck.Select(controlToCheck => MasterErrorProvider.GetError(controlToCheck)).FirstOrDefault(controlError => !string.IsNullOrEmpty(controlError));

            if (string.IsNullOrEmpty(error))
            {
                if (Employee == null)
                {
                    Employee = new Employee
                    {
                        Id = int.Parse(EmployeeIdTextBox.Text),
                        EntryDate = EmployeeEntryDateDateTimePicker.Value,
                        FirstName = EmployeeFirstNameTextBox.Text,
                        MiddleName = EmployeeMiddleNameTextBox.Text,
                        FirstSurname = EmployeeFirstSurnameTextBox.Text,
                        SecondSurname = EmployeeSecondSurnameTextBox.Text,
                        DocumentType = EmployeeDocumentTypeTextBox.Text.Trim(),
                        DocumentNumber = EmployeeDocumentNumberTextBox.Text.Trim(),
                        BirthDate = EmployeeBirthDateDateTimePicker.Value,
                        MaritalStatus = EnumHelper.LocalizedStringToMaritalStatus((string)EmployeeMaritalStatusComboBox.SelectedItem),
                        Position = EmployeePositionComboBox.SelectedItem != null ? Repository.Instance.Positions.Single(position => position.Name.Equals((string)EmployeePositionComboBox.SelectedItem, StringComparison.OrdinalIgnoreCase)) : (EmployeePositionCategoryComboBox.SelectedItem != null ? new Position { PositionCategory = EnumHelper.LocalizedStringToPositionCategory((string)EmployeePositionCategoryComboBox.SelectedItem) } : null),
                        FirstContactFirstName = EmployeeFirstContactFirstNameTextBox.Text,
                        FirstContactSurname = EmployeeFirstContactSurnameTextBox.Text,
                        FirstContactTelephoneNumber = EmployeeFirstContactTelephoneNumberTextBox.Text.Trim(),
                        FirstContactRelationship = EmployeeFirstContactRelationshipTextBox.Text.Trim()
                    };
                }
                else
                {
                    Employee.EntryDate = EmployeeEntryDateDateTimePicker.Value;
                    Employee.FirstName = EmployeeFirstNameTextBox.Text;
                    Employee.MiddleName = EmployeeMiddleNameTextBox.Text;
                    Employee.FirstSurname = EmployeeFirstSurnameTextBox.Text;
                    Employee.SecondSurname = EmployeeSecondSurnameTextBox.Text;
                    Employee.DocumentType = EmployeeDocumentTypeTextBox.Text.Trim();
                    Employee.DocumentNumber = EmployeeDocumentNumberTextBox.Text.Trim();
                    Employee.BirthDate = EmployeeBirthDateDateTimePicker.Value;
                    Employee.MaritalStatus = EnumHelper.LocalizedStringToMaritalStatus((string)EmployeeMaritalStatusComboBox.SelectedItem);
                    Employee.Position = EmployeePositionComboBox.SelectedItem != null ? Repository.Instance.Positions.Single(position => position.Name.Equals((string)EmployeePositionComboBox.SelectedItem, StringComparison.OrdinalIgnoreCase)) : (EmployeePositionCategoryComboBox.SelectedItem != null ? new Position { PositionCategory = EnumHelper.LocalizedStringToPositionCategory((string)EmployeePositionCategoryComboBox.SelectedItem) } : null);
                    Employee.FirstContactFirstName = EmployeeFirstContactFirstNameTextBox.Text;
                    Employee.FirstContactSurname = EmployeeFirstContactSurnameTextBox.Text;
                    Employee.FirstContactTelephoneNumber = EmployeeFirstContactTelephoneNumberTextBox.Text.Trim();
                    Employee.FirstContactRelationship = EmployeeFirstContactRelationshipTextBox.Text.Trim();
                }

                DialogResult = DialogResult.OK;
                Hide();
            }
            else
            {
                MessageBox.Show(this, error, Owner.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CancelNewUpdateEmployeeButton_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Hide();
        }
    }
}